package com.tian.interceptor;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.tian.annotation.SysLogAnnotation;
import com.tian.enums.SysLogTypeEnum;
import com.tian.factory.StrategyFactory;
import com.tian.message.SysLogMessage;
import com.tian.service.SysLogService;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.*;

/**
 * @author tianwc  公众号：java后端技术全栈、面试专栏
 * @version 1.0.0
 * @date 2022年11月01日 17:24
 *
 * 日志切面
 */
@Aspect
@Component
@Slf4j
public class WebLogAspect {
    @Resource
    private StrategyFactory strategyFactory;

    /**
     * 这里我们使用注解的形式
     * 当然，我们也可以通过切点表达式直接指定需要拦截的package,需要拦截的class 以及 method
     * 切点表达式:   execution(...)
     */
    @Pointcut("@annotation(com.tian.annotation.SysLogAnnotation)")
    public void webLog() {

    }

    /**
     * 接口请求参数、相应参数、耗时、路径等信息打印
     */
    @Around("webLog()")
    public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {
        long startTime = System.currentTimeMillis();
        //获取当前请求对象
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();

        Object result = joinPoint.proceed();

        String className = joinPoint.getTarget().getClass().getName();
        Signature signature = joinPoint.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        Method method = methodSignature.getMethod();

        SysLogAnnotation argsLogAnnotation = method.getAnnotation(SysLogAnnotation.class);

        String methodDescription = argsLogAnnotation.methodDescription();
        SysLogTypeEnum sysLogTypeEnum = argsLogAnnotation.type();
        long endTime = System.currentTimeMillis();
        String url = request.getRequestURL().toString();

        SysLogMessage sysLogMessage = SysLogMessage.builder().methodDesc(methodDescription).methodName(className + "#" + method.getName())
                .requestParam(JSON.toJSONString(getParameter(method, joinPoint.getArgs()))).ip(request.getRemoteAddr())
                .responseParam(JSON.toJSONString(result)).costTime((endTime - startTime)).createTime(new Date())
                .url(url).build();

        SysLogService sysLogService = strategyFactory.getInvokeStrategy(sysLogTypeEnum.getType());
        if (sysLogService == null) {
            log.info("sys log type is error,type={}", sysLogTypeEnum.getType());
            return result;
        }
        sysLogService.logRecord(sysLogMessage);
        return result;
    }

    /**
     * 根据方法和传入的参数获取请求参数
     */
    private Object getParameter(Method method, Object[] args) {
        List<Object> argList = new ArrayList<>();
        Parameter[] parameters = method.getParameters();
        for (int i = 0; i < parameters.length; i++) {
            //将RequestBody注解修饰的参数作为请求参数
            RequestBody requestBody = parameters[i].getAnnotation(RequestBody.class);
            if (requestBody != null) {
                argList.add(args[i]);
            }
            //将RequestParam注解修饰的参数作为请求参数
            RequestParam requestParam = parameters[i].getAnnotation(RequestParam.class);
            if (requestParam != null) {
                Map<String, Object> map = new HashMap<>();
                String key = parameters[i].getName();
                if (!StrUtil.isEmpty(requestParam.value())) {
                    key = requestParam.value();
                }
                map.put(key, args[i]);
                argList.add(map);
            }
        }
        if (argList.size() == 0) {
            return null;
        } else if (argList.size() == 1) {
            return argList.get(0);
        } else {
            return argList;
        }
    }
}
